package com.group525.cloudef.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.group525.cloudef.common.CommonResult;
import com.group525.cloudef.entity.admin.User;
import com.group525.cloudef.service.admin.userService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group525.cloudef.utils.JwtUtil;
import com.group525.cloudef.utils.Md5Util;
import org.springframework.stereotype.Service;
import com.group525.cloudef.mapper.admin.UserMapper;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;



/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author group525
 * @since 2023-01-31
 */
@Service
public class userServiceImpl extends ServiceImpl<UserMapper, User> implements userService {

    @Resource
    UserMapper userMapper;

    @Resource
    Md5Util md5Util;

    @Resource
    JwtUtil jwtUtil;

    /**
     *
     * @param user (前端封装的对象)
     * @return 统一结果集
     */
    @Override
    public CommonResult<?> login(User user) {
        //0.获取用户输入的username与password
        String username = user.getUsername();
        String password = user.getPassword();
        //1.QueryWrapper进行筛选条件
            QueryWrapper<User>queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("username",username);
            User userFormDataBase = userMapper.selectOne(queryWrapper);
            //相当于SELECT username,password FROM user WHERE status=0 AND (username = ?)

        //2.创建Optional对象将User对象进行封装（对付空指针异常问题）
            Optional<User> userNameOptional = Optional.ofNullable(userFormDataBase);
            //2.1如果username存在
            if(userNameOptional.isPresent()){
                //3.进行密码的比对
                //if( md5Util.isCorrect(userFormDataBase.getPassword(),password))
                if(Objects.equals(password, userFormDataBase.getPassword())) {
                    //3.1 如果密码正确生成token给前端
                    String token = jwtUtil.createJWT(username);

                    return CommonResult.success("登录成功",userFormDataBase);

                }else {
                    //3.2 密码不正确
                    return CommonResult.failed("密码错误");
                }
            }else{
                    //2.2如果username不存在
                return CommonResult.failed("用户不存在");
            }

    }
}
